const http = require("http");
const fs = require("fs");
const app = http.createServer((req, res) => {
  const { method, url } = req;
  console.log("cookie", req.headers.cookie);
  if (method == "GET" && url == "/") {
    fs.readFile("./index.html", (err, data) => {
      res.setHeader("Content-Type", "text/html");
      res.end(data);
    });
  } else if ((method == "GET" || method == "POST") && url == "/api/users") {
    res.setHeader("Content-Type", "application/json");
    // 允许携带cookie
    res.setHeader("Access-Control-Allow-Credentials", "true");
    // 设置cookie
    res.setHeader("Set-Cookie", "cookie1=va222;");
    res.end(
      JSON.stringify([
        {
          name: "tom",
          age: 20,
        },
      ])
    );
  } else if (method == "OPTIONS" && url == "/api/users") {
    // 允许接收cookie
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.end();
  } else if (method === "POST" && url === "/api/save") {
    let reqData = [];
    let size = 0;
    req.on("data", (data) => {
      console.log(">>>req on", data);
      reqData.push(data);
      size += data.length;
    });
    req.on("end", function () {
      console.log("end");
      const data = Buffer.concat(reqData, size);
      console.log("data:", size, data.toString());
      res.end(`formdata:${data.toString()}`);
    });
  }
});
module.exports = app;
